/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.ext.echarts.builder.model;

import org.zkoss.io.Serializables;

import java.util.LinkedList;
import java.util.List;

public abstract class AbstractEChartsModel implements EChartsModel,
        java.io.Serializable {
    protected List<EChartsDataListener> _listeners = new LinkedList<EChartsDataListener>();


    protected void fireEvent(int type, Comparable<?> series,
                             Comparable<?> category, int seriesIndex, int categoryIndex,
                             Object data) {
        final EChartsDataEvent evt = new EChartsDataEventImpl(this, type, series,
                category, seriesIndex, categoryIndex, data);
        for (EChartsDataListener l : _listeners)
            l.onChange(evt);
    }

    // -- ChartsModel --//
    public void addChartsDataListener(EChartsDataListener l) {
        if (l == null)
            throw new NullPointerException();
        _listeners.add(l);
    }

    public void removeChartsDataListener(EChartsDataListener l) {
        _listeners.remove(l);
    }

    // Serializable//
    private synchronized void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        s.defaultWriteObject();

        Serializables.smartWrite(s, _listeners);
    }

    private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();

        _listeners = new LinkedList<EChartsDataListener>();
        Serializables.smartRead(s, _listeners);
    }

    public Object clone() {
        final AbstractEChartsModel clone;
        try {
            clone = (AbstractEChartsModel) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
        clone._listeners = new LinkedList<EChartsDataListener>();
        return clone;
    }

}
